package com.heiye.blog.ai.strategy.sound.impl;

import com.heiye.blog.ai.convert.TTSConvert;
import com.heiye.blog.ai.enums.SoundModelTypeEnum;
import com.heiye.blog.ai.model.dto.TTSRequest;
import com.heiye.blog.ai.model.gptsovits.GPTSoVITSApi;
import com.heiye.blog.ai.model.gptsovits.GPTSoVITSOptions;
import com.heiye.blog.ai.rpc.OSSRpcService;
import com.heiye.blog.ai.strategy.sound.SoundModelStrategy;
import com.heiye.blog.framework.common.response.Response;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

/**
 * @author: heiye
 * @date: 2025/11/20 下午3:02
 * @version: v1.0.0
 * @description: GPT-SoVITS V2 Pro Plus 模型策略实现类
 */
@Slf4j
@Component
public class GPTSoVITSV2ProPlusStrategy implements SoundModelStrategy {

    @Value("${spring.tts.gpt-sovits.base-url}")
    private String baseUrl;

    @Resource
    private WebClient.Builder webClientBuilder;

    @Resource
    private OSSRpcService ossRpcService;

    /**
     * 获取模型名称和版本
     *
     * @return
     */
    @Override
    public SoundModelTypeEnum getSoundModelTypeEnum() {
        return SoundModelTypeEnum.GPT_SOVITS_V2_PRO_PLUS;
    }

    /**
     * 生成语音
     *
     * @param ttsRequest
     * @return
     */
    @Override
    public String generation(TTSRequest ttsRequest) {

        // 创建 GPTSoVITS Options 默认值
        GPTSoVITSOptions options = GPTSoVITSOptions.builder().build();

        // 覆盖 GPTSoVITS Options
        TTSConvert.INSTANCE.updateGPTSoVITSOptionsFromRequest(ttsRequest, options);

        // 填入缩写的模型名
        options.setModel(getSoundModelTypeEnum().getSimpleName());

        // 创建 GPT-SoVITS Api
        GPTSoVITSApi api = GPTSoVITSApi.builder()
                .baseUrl(baseUrl)
                .webClientBuilder(webClientBuilder)
                .build();

        // 调用 GPT-SoVITS Api 生成语音
        Flux<DataBuffer> generation = api.generation(options);

        // 调用 OSS RPC 服务生成音频链接
        return ossRpcService.audioStreamUpload(generation, options.getMediaType()).block();
    }

    /**
     * 对参数进行审查
     *
     * @param ttsRequest
     * @return
     */
    @Override
    public void reviewAndOptimizeRequest(TTSRequest ttsRequest) {
    }
}
